"""
v0 script written by Myriam Benisty and Stefano Facchini (Feb 2st 2022)
v1 version adapted by Stefano Facchini and Myriam Benisty (Mar 2nd 2022)
v2 version adapted to include ACA data by Jane Huang and compacted code by Gianni Cataldi (May 19th 2022)
v3 (current version) includes EB alignment by Ryan Loomis and Richard Teague (Aug 2022)


This script is written for CASA 6.2.1.7. 
It can easily be adapted to other versions of CASA, e.g. by modifying the fixvis task to phaseshift task.

The numba package is used for the alignment script, but it is not necessary (it helps with the speed-up)

The scripts are written to be compatible mpicasa.
However, after testingthe exoALMA collaboration decided not to use mpicasa in any of the calibration scripts,
since they realized that differences in the results between casa and mpicasa could arise.

Person in charge for this source:
H. Yen

"""

import os
import numpy as np
import shutil
import matplotlib
#increase the number of figures that can be open before issuing a warning
matplotlib.rcParams.update({'figure.max_open_warning':80})

#path to your local copy of the gihub repository
#(make sure to do a 'git pull' to have the most up-to-date version)
github_path = '/users/hyen/calibration_scripts'
import sys
sys.path.append(github_path)
import alignment
execfile(os.path.join(github_path,'reduction_utils_exoalma.py'))

prefix = 'RXJ1842-3532'

data_folderpath = '/lustre/cv/projects/exoALMA/ALMA_PL_calibrated_data/J1842-3532'
TM_names = {'LB':'TM1','SB':'TM2'}
PL_calibrated_vis = {key:os.path.join(data_folderpath,f'{TM_name}/calibrated_final.ms')
                     for key,TM_name in TM_names.items()}

for baseline_key,TM_name in TM_names.items():
    listobs(
        vis=PL_calibrated_vis[baseline_key],
        listfile=f'{prefix}_{TM_name}_calibrated_final.ms.txt',
        overwrite=True,
    )


# System properties.
incl =  32. # Francis & van der Marel 2020
PA = 30   # deg
v_sys = 6.2 # km/s; use the one from listobs

# Whether to run tclean in parallel or not.
use_parallel = True

fields = {'SB':'RXJ1842.9-3532','LB':'RXJ1842.9-3532'}

number_of_EBs = {'SB':2,'LB':5}

for baseline_key,vis in PL_calibrated_vis.items():
    split_all_obs(msfile=vis,nametemplate=f'{prefix}_{baseline_key}_EB')

for baseline_key,n_EB in number_of_EBs.items():
    for i in range(n_EB):
        vis = f'{prefix}_{baseline_key}_EB{i}.ms'
        listobs(
            vis=vis,
            listfile=f'{vis}.txt',
            overwrite=True,
        )

"""
Check that spws and field numbering is what you expect them to be now from the listobs files
In particular, make sure that there are 4 spws and that there is a single field with
field ID = 0
"""

# Line rest frequencies from splatalogue (https://splatalogue.online)
rest_freq_12CO = 345.79598990e9 #J=3-2
rest_freq_13CO = 330.58796530e9 #J=3-2 (ignoring splitting)
rest_freq_CS   = 342.88285030e9 #J=7-6

data_params_LB = {f'LB{i}': {'vis' : f'{prefix}_LB_EB{i}.ms',
                             'name' : f'LB_EB{i}',
                             'field' : fields['LB'],
                             'line_spws': np.array([0,2,3]), # list of spws containing lines
                             'line_freqs': np.array([rest_freq_13CO,rest_freq_CS,rest_freq_12CO]), #frequencies (Hz) corresponding to line_spws
                             'cont_spws': None,
                             'width_array': None,
                             }
                  for i in range(number_of_EBs['LB'])}

data_params_SB = {f'SB{i}': {'vis' : f'{prefix}_SB_EB{i}.ms',
                             'name' : f'SB_EB{i}',
                             'field' : fields['SB'],
                             'line_spws': np.array([0,2,3]), # list of spws containing lines
                             'line_freqs': np.array([rest_freq_13CO,rest_freq_CS,rest_freq_12CO]), #frequencies (Hz) corresponding to line_spws
                             'cont_spws': None,
                             'width_array': None,
                             }
                  for i in range(number_of_EBs['SB'])}


data_params = data_params_LB.copy()
data_params.update(data_params_SB)

figures_foldername = 'figures'
os.mkdir(figures_foldername)

def get_figures_folderpath(foldername):
    return os.path.join(figures_foldername,foldername)

def make_figures_folder(folderpath):
    if os.path.isdir(folderpath):
        print(f'going to deleted folder {folderpath} and its content')
        valid_answer = 'yes'
        answer = input(f'to confirm, type \'{valid_answer}\': ')
        if answer == valid_answer:
            shutil.rmtree(folderpath)
        else:
            print('aborting')
            return
    os.mkdir(folderpath)
    return folderpath

preselfcal_amp_figures_folder = get_figures_folderpath('1_preselfcal_amp_figures')
make_figures_folder(preselfcal_amp_figures_folder)

#adjust these plot ranges according to your data
plotranges = {'SB':[0,600,0,0.2],#xmin,xmax,ymin,ymax
              'LB':[0,3000,0,0.2]}

for params in data_params.values():
    plot_filename = prefix+'_'+params['name']+'_chan-v-amp_preselfcal.png'
    plotms(vis=params['vis'],
            xaxis='channel',
            yaxis='amplitude',
            field=params['field'],
            ydatacolumn='data',
            avgtime='1e8',
            avgscan=True,
            avgbaseline=True,
            iteraxis='spw',
            #There is a bug in plotms that plots the data wrongly if there is unequal flagging
            #between the polarisations
            #the bug occurs if we plot amp and we average over baselines
            #thus we color by polarization such that
            #we easily identify this issue
            coloraxis='corr', 
            showgui = False,
            exprange='all',
            plotfile=os.path.join(preselfcal_amp_figures_folder,plot_filename)
            )
    baseline_key,_ = params['name'].split('_')
    plotms(vis=params['vis'],
           xaxis='UVdist',
           yaxis='amplitude',
           spw='1',
           field=params['field'],
           ydatacolumn='data',
           avgtime='1e8',
           avgscan=True,
           avgchannel='3840',
           showgui = False,
           plotrange=plotranges[baseline_key],
           plotfile=os.path.join(preselfcal_amp_figures_folder,
                                 prefix+'_'+params['name']+'_uvdist-v-amp_cont_spw_preselfcal.png')
           )

for params in data_params.values():
    flagchannels_string = get_flagchannels(ms_dict=params,output_prefix=prefix,
                                           velocity_range=np.array([-15.,15.])+v_sys)
    avg_cont(ms_dict=params,output_prefix=prefix,flagchannels=flagchannels_string,
             contspws=params['cont_spws'],width_array=params['width_array'])
# Flagchannels input string for LB_EB0: '0:835~3003, 2:795~3044, 3:785~3053'
# Flagchannels input string for LB_EB1: '0:835~3003, 2:795~3044, 3:785~3053'
# Flagchannels input string for LB_EB2: '0:835~3003, 2:796~3044, 3:784~3052'
# Flagchannels input string for LB_EB3: '0:835~3003, 2:796~3044, 3:784~3052'
# Flagchannels input string for LB_EB4: '0:835~3003, 2:796~3044, 3:784~3052'
# Flagchannels input string for SB_EB0: '0:838~3006, 2:791~3040, 3:791~3059'
# Flagchannels input string for SB_EB1: '0:838~3006, 2:791~3040, 3:791~3059'

"""
Double-check that the channels idenfied are at the center of the spws,
due to a potential issue with the data_desc_id key in the ms table of some programs
"""


preselfcal_initcont_amp_folder = get_figures_folderpath(
                                  '2_preselfcal_initcont_amp_figures')
make_figures_folder(preselfcal_initcont_amp_folder)

uv_ranges = {'LB':'125~150m','SB':'125~150m'}

for params in data_params.values():
    vis = prefix+'_'+params['name']+'_initcont.ms'
    baseline_key = params['name'].split('_')[0]
    plotms(vis=vis,
            xaxis='UVdist',
            overwrite=True,
            yaxis='amp',
            coloraxis='spw',
            avgtime='1e8',
            avgscan=True,
            showgui=False,
            plotrange=plotranges[baseline_key],
            plotfile=os.path.join(preselfcal_initcont_amp_folder,
                                  prefix+'_'+params['name']+'_uvdist-v-amp_initcont_preselfcal.png'))

    plotms(vis=vis,
            xaxis='time',
            yaxis='amp',
            avgspw=True,
            uvrange=uv_ranges[baseline_key],
            avgchannel='10000',
            avgbaseline=True,
            coloraxis='corr',
            showgui=False,
            overwrite=True,
            plotfile=os.path.join(preselfcal_initcont_amp_folder,
                                  prefix+'_'+params['name']+'_amp_v_time_initcont_preselfcal.png')
            )
#check if there are "waterfall features" (times where the amp suddently sharply decreases)
#if so, we will try to fix this with self-cal


""" Define simple masks and clean scales for imaging """
mask_pa = PA #position angle of mask in degrees
mask_semimajor = 1.5 #semimajor axis of mask in arcsec
mask_semiminor = mask_semimajor*np.cos(incl/180.*np.pi) #semiminor axis of mask in arcsec
mask_ra = '18h42m57.983674s' #taken from listobs
mask_dec = '-35.32.43.43712'

mask = f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor:.3f}arcsec,'\
            + f' {mask_semiminor:.3f}arcsec], {mask_pa:.1f}deg]'
# Cellsize: ~beam/6-7
cellsize =  {'LB':'0.015arcsec','SB':'0.060arcsec'}
# Image size: ~primary beam 1.22*lam/A = 32'' with A=12m (19 arcsec)
imsize = {'LB':1200,'SB':400}# primary beam
scales = {'LB':[0,8,15,30,80],'SB':[0,8,15,30]}

noise_annulus = f"annulus[[{mask_ra}, {mask_dec}],['4.arcsec', '6.arcsec']]"
thresholds = {'LB':'0.6mJy','SB':'2mJy'} #clean down to 6 sigma for phase cal

image_png_plot_sizes = [3,10] #sizes in arcsec of the zoomed and overview plots of the pngs

preselfcal_images_png_folder = get_figures_folderpath('3_preselfcal_images')
make_figures_folder(preselfcal_images_png_folder)

for baseline_key,params in zip(('LB','SB'),(data_params_LB,data_params_SB)):
    for EB_key,p in params.items():
        imagename = prefix+'_'+p['name']+'_initcont_image'
        tclean_wrapper(
                      vis=prefix+'_'+p['name']+'_initcont.ms',
                      imagename=imagename,
                      deconvolver='multiscale',
                      scales=scales[baseline_key],
                      mask=mask,
                      threshold=thresholds[baseline_key],
                      cellsize=cellsize[baseline_key],
                      imsize=imsize[baseline_key],
                      parallel=use_parallel,
                      savemodel='modelcolumn'
                    )
        estimate_SNR(f'{imagename}.image',disk_mask=mask,noise_mask=noise_annulus)
        rms = imstat(imagename=f'{imagename}.image',region=noise_annulus)['rms'][0]
        params[EB_key]['rms'] = rms
        generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes,
                            color_scale_limits=[-3*rms,10*rms],
                            save_folder=preselfcal_images_png_folder)
#RXJ1842-3532_LB_EB0_initcont_image.image
#Beam 0.165 arcsec x 0.099 arcsec (45.33 deg)
#Flux inside disk mask: 137.08 mJy
#Peak intensity of source: 6.29 mJy/beam
#rms: 8.65e-02 mJy/beam
#Peak SNR: 72.77
#RXJ1842-3532_LB_EB1_initcont_image.image
#Beam 0.138 arcsec x 0.089 arcsec (84.44 deg)
#Flux inside disk mask: 139.79 mJy
#Peak intensity of source: 5.15 mJy/beam
#rms: 8.85e-02 mJy/beam
#Peak SNR: 58.23
#RXJ1842-3532_LB_EB2_initcont_image.image
#Beam 0.149 arcsec x 0.097 arcsec (-87.02 deg)
#Flux inside disk mask: 148.14 mJy
#Peak intensity of source: 6.39 mJy/beam
#rms: 1.16e-01 mJy/beam
#Peak SNR: 55.22
#RXJ1842-3532_LB_EB3_initcont_image.image
#Beam 0.109 arcsec x 0.099 arcsec (81.00 deg)
#Flux inside disk mask: 142.77 mJy
#Peak intensity of source: 5.04 mJy/beam
#rms: 6.73e-02 mJy/beam
#Peak SNR: 74.85
#RXJ1842-3532_LB_EB4_initcont_image.image
#Beam 0.130 arcsec x 0.099 arcsec (84.96 deg)
#Flux inside disk mask: 142.35 mJy
#Peak intensity of source: 5.42 mJy/beam
#rms: 8.34e-02 mJy/beam
#Peak SNR: 65.01
#RXJ1842-3532_SB_EB0_initcont_image.image
#Beam 0.555 arcsec x 0.435 arcsec (79.71 deg)
#Flux inside disk mask: 124.51 mJy
#Peak intensity of source: 45.22 mJy/beam
#rms: 3.11e-01 mJy/beam
#Peak SNR: 145.20
#RXJ1842-3532_SB_EB1_initcont_image.image
#Beam 0.570 arcsec x 0.526 arcsec (39.62 deg)
#Flux inside disk mask: 137.58 mJy
#Peak intensity of source: 59.02 mJy/beam
#rms: 3.36e-01 mJy/beam
#Peak SNR: 175.68


######
# SELF-CAL INDIVIDUAL EBs
######
""" Self-calibration parameters """
single_EB_contspws = '0~3'
single_EB_spw_mapping = [0,0,0,0]

individual_EB_selfcal_shift_folder = get_figures_folderpath(
                                                   '4_individual_EB_selfcal_and_shift_figures')
make_figures_folder(individual_EB_selfcal_shift_folder)

""" One round of phase-only self-cal """
for params in data_params.values():
    vis = prefix+'_'+params['name']+'_initcont.ms'
    single_EB_p1 = prefix+'_'+params['name']+'_initcont.p1'
    os.system(f'rm -rf {single_EB_p1}')
    gaincal(vis=vis,caltable=single_EB_p1,gaintype='T',spw=single_EB_contspws,
            combine='scan,spw',calmode='p',solint='inf',minsnr=4,minblperant=3)
    """ Print calibration png file """
    plotfilename = prefix+'_'+params['name']\
                        +'_initcont_gain_p1_phase_vs_time.png'
    plotms(single_EB_p1,xaxis='time',yaxis='GainPhase',overwrite=True,showgui=False,
           plotfile=os.path.join(individual_EB_selfcal_shift_folder,plotfilename))
    """ Apply the solutions """
    applycal(vis=vis,spw=single_EB_contspws,spwmap=single_EB_spw_mapping,
             gaintable=[single_EB_p1],interp='linearPD',applymode='calonly',calwt=True)
    split(vis=vis,outputvis=prefix+'_'+params['name']+'_initcont_selfcal.ms',
          datacolumn='corrected')


### Image self-cal'd EBs ###

for baseline_key,params in zip(('LB','SB'),(data_params_LB,data_params_SB)):
    for p in params.values():
        imagename = prefix+'_'+p['name']+'_initcont_selfcal_image'
        tclean_wrapper(vis=prefix+'_'+p['name']+'_initcont_selfcal.ms',
                        imagename=imagename,
                        deconvolver='multiscale',
                        scales=scales[baseline_key],
                        mask=mask,
                        threshold=thresholds[baseline_key],
                        cellsize=cellsize[baseline_key],
                        imsize=imsize[baseline_key],
                        parallel=use_parallel,
                        )
        output_image = f'{imagename}.image'
        estimate_SNR(output_image,disk_mask=mask,noise_mask=noise_annulus)
        rms = p['rms']
        generate_image_png(image=output_image,plot_sizes=image_png_plot_sizes,
                           color_scale_limits=[-3*rms,10*rms],
                           save_folder=individual_EB_selfcal_shift_folder)
#RXJ1842-3532_LB_EB0_initcont_selfcal_image.image
#Beam 0.165 arcsec x 0.099 arcsec (45.33 deg)
#Flux inside disk mask: 137.22 mJy
#Peak intensity of source: 6.23 mJy/beam
#rms: 7.61e-02 mJy/beam
#Peak SNR: 81.90
#RXJ1842-3532_LB_EB1_initcont_selfcal_image.image
#Beam 0.138 arcsec x 0.089 arcsec (84.44 deg)
#Flux inside disk mask: 140.15 mJy
#Peak intensity of source: 5.27 mJy/beam
#rms: 7.85e-02 mJy/beam
#Peak SNR: 67.19
#RXJ1842-3532_LB_EB2_initcont_selfcal_image.image
#Beam 0.149 arcsec x 0.097 arcsec (-87.02 deg)
#Flux inside disk mask: 147.69 mJy
#Peak intensity of source: 6.64 mJy/beam
#rms: 1.05e-01 mJy/beam
#Peak SNR: 63.06
#RXJ1842-3532_LB_EB3_initcont_selfcal_image.image
#Beam 0.109 arcsec x 0.099 arcsec (81.00 deg)
#Flux inside disk mask: 143.54 mJy
#Peak intensity of source: 5.08 mJy/beam
#rms: 5.79e-02 mJy/beam
#Peak SNR: 87.75
#RXJ1842-3532_LB_EB4_initcont_selfcal_image.image
#Beam 0.130 arcsec x 0.099 arcsec (84.96 deg)
#Flux inside disk mask: 144.14 mJy
#Peak intensity of source: 5.55 mJy/beam
#rms: 6.93e-02 mJy/beam
#Peak SNR: 80.03
#RXJ1842-3532_SB_EB0_initcont_selfcal_image.image
#Beam 0.555 arcsec x 0.435 arcsec (79.71 deg)
#Flux inside disk mask: 131.83 mJy
#Peak intensity of source: 47.49 mJy/beam
#rms: 8.90e-02 mJy/beam
#Peak SNR: 533.51
#RXJ1842-3532_SB_EB1_initcont_selfcal_image.image
#Beam 0.570 arcsec x 0.526 arcsec (39.62 deg)
#Flux inside disk mask: 140.61 mJy
#Peak intensity of source: 60.30 mJy/beam
#rms: 1.10e-01 mJy/beam
#Peak SNR: 547.91


for baseline_key,params in zip(('LB','SB'),(data_params_LB,data_params_SB)):
    for p in params.values():
        imagename = prefix+'_'+p['name']+'_initcont_selfcal_image'
        #ratio image, to be compared to the ratio image after alignment
        ref_image = f'{prefix}_{baseline_key}_EB0_initcont_selfcal_image.image'
        ref_rms = params[f'{baseline_key}0']['rms']
        ratio_image = imagename+'.ratio'
        os.system(f'rm -rf {ratio_image}')
        immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
               outfile=ratio_image,expr=f'iif(IM0 > 3*{ref_rms}, IM1/IM0, 0)')
        generate_image_png(ratio_image,plot_sizes=[2*mask_semimajor,2*mask_semimajor],
                           color_scale_limits=[0.5,1.5],image_units='ratio',
                           save_folder=individual_EB_selfcal_shift_folder)

######
# ALIGN DATA (go from *initcont_selfcal.ms to *initcont_shift.ms)
######

# Select the LB EB to act as the reference (usually the best SNR one).

reference_for_LB_alignment = f'{prefix}_LB_EB3_initcont_selfcal.ms'
assert 'LB' in reference_for_LB_alignment,\
            'you need to choose an LB EB for alignment of LB'

alignment_offsets = {}

# All the other EBs will be aligned to the reference EB
# We also include the reference EB itself to make sure the coordinate changes are
# copied over.

offset_LB_EBs = ['{}_{}_initcont_selfcal.ms'.format(prefix, params['name'])
                 for params in data_params_LB.values()]

#select the continuum spw with the large bandwidth
continuum_spw_id = 1
# Find the relative offsets and update the phase centers for all offset_EBs.
npix = 128 
cell_size = 0.01 
alignment.align_measurement_sets(reference_ms=reference_for_LB_alignment,
                                 align_ms=offset_LB_EBs,npix=npix,cell_size=cell_size,
                                 spwid=continuum_spw_id)
#New coordinates for RXJ1842-3532_LB_EB0_initcont_selfcal.ms
#requires a shift of [0.0012236,0.0058322]
#New coordinates for RXJ1842-3532_LB_EB1_initcont_selfcal.ms
#requires a shift of [0.0021059,-0.0011211]
#New coordinates for RXJ1842-3532_LB_EB2_initcont_selfcal.ms
#requires a shift of [0.0089469,-0.00041544]
#New coordinates for RXJ1842-3532_LB_EB3_initcont_selfcal.ms
#no shift, reference MS.
#New coordinates for RXJ1842-3532_LB_EB4_initcont_selfcal.ms
#requires a shift of [0.0065379,-0.00036901]
#using 512 & 0.0025 gives the same result


#insert offsets from the alignment output
alignment_offsets['LB_EB0'] = [0.0012236,0.0058322]
alignment_offsets['LB_EB1'] = [0.0021059,-0.0011211]
alignment_offsets['LB_EB2'] = [0.0089469,-0.00041544]
alignment_offsets['LB_EB3'] = [0,0]
alignment_offsets['LB_EB4'] = [0.0065379,-0.00036901]

shifted_LB_EBs = [EB.replace('.ms','_shift.ms') for EB in offset_LB_EBs]

#to check if alignment worked, calculate shift again and verify that shifts are small (i.e.
#a fraction of the cell size):

for shifted_ms in shifted_LB_EBs:
    if shifted_ms == reference_for_LB_alignment.replace('.ms','_shift.ms'):
        #for some reason the fitter fails when computing the offset of an EB to itself,
        #so we skip the ref EB
        continue
    offset = alignment.find_offset(reference_ms=reference_for_LB_alignment,
                                   offset_ms=shifted_ms,npix=npix,cell_size=cell_size,
                                   spwid=continuum_spw_id)
    print(f'#offset for {shifted_ms}: ',offset)
#offset for RXJ1842-3532_LB_EB0_initcont_selfcal_shift.ms:  [0.00125814 0.00132945]
#offset for RXJ1842-3532_LB_EB1_initcont_selfcal_shift.ms:  [ 1.00654446e-03 -4.02761844e-05]
#offset for RXJ1842-3532_LB_EB2_initcont_selfcal_shift.ms:  [0.00208326 0.00083583]
#offset for RXJ1842-3532_LB_EB4_initcont_selfcal_shift.ms:  [ 0.0020769  -0.00015939]


# Merge shifted LB EBs for aligning SB EBs
LB_concat_shifted = f'{prefix}_LB_concat_shifted.ms'
os.system(f'rm -rf {LB_concat_shifted}')
concat(vis=shifted_LB_EBs,concatvis=LB_concat_shifted,dirtol='0.1arcsec',
       copypointing=False)

npix=2048
cell_size=0.02

# Align SB EBs to concat shifted LB EBs
reference_for_SB_alignment = LB_concat_shifted

offset_SB_EBs = ['{}_{}_initcont_selfcal.ms'.format(prefix, params['name'])
                 for params in data_params_SB.values()]

alignment.align_measurement_sets(reference_ms=reference_for_SB_alignment,
                                 align_ms=offset_SB_EBs,npix=npix,cell_size=cell_size,
                                 spwid=continuum_spw_id)

#New coordinates for RXJ1842-3532_SB_EB0_initcont_selfcal.ms
#requires a shift of [-0.044149,0.0006274]
#New coordinates for RXJ1842-3532_SB_EB1_initcont_selfcal.ms
#requires a shift of [-0.028745,0.0020227]


alignment_offsets['SB_EB0'] = [-0.044149,0.0006274]
alignment_offsets['SB_EB1'] = [-0.028745,0.0020227]

shifted_SB_EBs = [EB.replace('.ms','_shift.ms') for EB in offset_SB_EBs]

#check by calculating offset again
for shifted_ms in shifted_SB_EBs:
    offset = alignment.find_offset(reference_ms=reference_for_SB_alignment,
                                   offset_ms=shifted_ms,npix=npix,cell_size=cell_size,
                                   spwid=continuum_spw_id)
    print(f'#offset for {shifted_ms}: ',offset)
#offset for RXJ1842-3532_SB_EB0_initcont_selfcal_shift.ms:  [-6.19986788e-05 -1.22684840e-05]
#offset for RXJ1842-3532_SB_EB1_initcont_selfcal_shift.ms:  [ 0.00056132 -0.00011373]


# Remove the '_selfcal' part of the names to match the naming convention below.
for shifted_EB in shifted_LB_EBs+shifted_SB_EBs:
    os.system('mv {} {}'.format(shifted_EB, shifted_EB.replace('_selfcal', '')))


""" Check that the images are indeed aligned after the shift """

for baseline_key,params in zip(('LB','SB'),(data_params_LB,data_params_SB)):
    for p in params.values():
        imagename = prefix+'_'+p['name']+'_initcont_shift_image'
        tclean_wrapper(vis=prefix+'_'+p['name']+'_initcont_shift.ms',
                        imagename=imagename,
                        deconvolver='multiscale',
                        scales=scales[baseline_key],
                        mask=mask,
                        threshold=thresholds[baseline_key],
                        cellsize=cellsize[baseline_key],
                        imsize=imsize[baseline_key],
                        parallel=use_parallel,
                      )
        estimate_SNR(f'{imagename}.image',disk_mask=mask,
                     noise_mask=noise_annulus)
        rms = p['rms']
        generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes,
                           color_scale_limits=[-3*rms,10*rms],
                           save_folder=individual_EB_selfcal_shift_folder)
#RXJ1842-3532_LB_EB0_initcont_shift_image.image
#Beam 0.165 arcsec x 0.099 arcsec (45.33 deg)
#Flux inside disk mask: 137.61 mJy
#Peak intensity of source: 6.22 mJy/beam
#rms: 7.60e-02 mJy/beam
#Peak SNR: 81.93
#RXJ1842-3532_LB_EB1_initcont_shift_image.image
#Beam 0.138 arcsec x 0.089 arcsec (84.44 deg)
#Flux inside disk mask: 139.77 mJy
#Peak intensity of source: 5.26 mJy/beam
#rms: 7.87e-02 mJy/beam
#Peak SNR: 66.87
#RXJ1842-3532_LB_EB2_initcont_shift_image.image
#Beam 0.149 arcsec x 0.097 arcsec (-87.03 deg)
#Flux inside disk mask: 148.92 mJy
#Peak intensity of source: 6.68 mJy/beam
#rms: 1.06e-01 mJy/beam
#Peak SNR: 63.31
#RXJ1842-3532_LB_EB3_initcont_shift_image.image
#Beam 0.109 arcsec x 0.099 arcsec (81.00 deg)
#Flux inside disk mask: 143.28 mJy
#Peak intensity of source: 5.10 mJy/beam
#rms: 5.82e-02 mJy/beam
#Peak SNR: 87.74
#RXJ1842-3532_LB_EB4_initcont_shift_image.image
#Beam 0.130 arcsec x 0.099 arcsec (84.96 deg)
#Flux inside disk mask: 143.86 mJy
#Peak intensity of source: 5.54 mJy/beam
#rms: 6.93e-02 mJy/beam
#Peak SNR: 79.92
#RXJ1842-3532_SB_EB0_initcont_shift_image.image
#Beam 0.555 arcsec x 0.435 arcsec (79.71 deg)
#Flux inside disk mask: 131.81 mJy
#Peak intensity of source: 47.54 mJy/beam
#rms: 8.91e-02 mJy/beam
#Peak SNR: 533.46
#RXJ1842-3532_SB_EB1_initcont_shift_image.image
#Beam 0.570 arcsec x 0.526 arcsec (39.62 deg)
#Flux inside disk mask: 140.62 mJy
#Peak intensity of source: 60.28 mJy/beam
#rms: 1.11e-01 mJy/beam
#Peak SNR: 542.46


for baseline_key,params in zip(('LB','SB'),(data_params_LB,data_params_SB)):
    for p in params.values():
        imagename = prefix+'_'+p['name']+'_initcont_shift_image'
        ref_image = f'{prefix}_{baseline_key}_EB0_initcont_shift_image.image'
        ref_rms = params[f'{baseline_key}0']['rms']
        ratio_image = imagename+'.ratio'
        os.system(f'rm -rf {ratio_image}')
        immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
               outfile=ratio_image,expr=f'iif(IM0 > 3*{ref_rms}, IM1/IM0, 0)')
        generate_image_png(ratio_image,plot_sizes=[2*mask_semimajor,2*mask_semimajor],
                           color_scale_limits=[0.5,1.5],image_units='ratio',
                           save_folder=individual_EB_selfcal_shift_folder)


""" Now that everything is aligned, we inspect the flux calibration. """

for params in data_params.values():
    msfile = prefix+'_'+params['name']+'_initcont_shift.ms'
    export_MS(msfile) #export MS contents into Numpy save files

""" Plot deprojected visibility profiles for all data together """
list_npz_files = []
for baseline_key,n_EB in number_of_EBs.items():
    list_npz_files += [f'{prefix}_{baseline_key}_EB{i}_initcont_shift.vis.npz'
                       for i in range(n_EB)]

deprojected_vis_profiles_folder = get_figures_folderpath('5_deprojected_vis_profiles')
make_figures_folder(deprojected_vis_profiles_folder)

plot_deprojected(filelist=list_npz_files,
                 fluxscale=[1.]*(number_of_EBs['LB']+number_of_EBs['SB']),PA=PA,
                 incl=incl,show_err=True,
                 plot_label=os.path.join(deprojected_vis_profiles_folder,
                                         f'{prefix}_flux_scale_EB_preselfcal.png'))

flux_comparison_folder = get_figures_folderpath('6_flux_comparisons')
make_figures_folder(flux_comparison_folder)

#we choose an EB to compare the flux scaling; if possible the best SB EB, but in the
#case of CQ Tau, SB sufferts from decoherence, so we choose an LB EB instead
flux_ref_EB = 'SB_EB1'

for params in data_params.values():
    plot_label = os.path.join(flux_comparison_folder,
                              'flux_comparison_'+params['name']+f'_to_{flux_ref_EB}.png')
    estimate_flux_scale(reference=f'{prefix}_{flux_ref_EB}_initcont_shift.vis.npz',
                        comparison=prefix+'_'+params['name']+'_initcont_shift.vis.npz',
                        incl=incl, PA=PA,plot_label=plot_label)

#Measurement set exported to RXJ1842-3532_SB_EB1_initcont_shift.vis.npz
#The ratio of the fluxes of RXJ1842-3532_LB_EB0_initcont_shift.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 0.97390
#The scaling factor for gencal is 0.987 for your comparison measurement
#The error on the weighted mean ratio is 9.143e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_LB_EB1_initcont_shift.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 0.98315
#The scaling factor for gencal is 0.992 for your comparison measurement
#The error on the weighted mean ratio is 1.040e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_LB_EB2_initcont_shift.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 1.02532
#The scaling factor for gencal is 1.013 for your comparison measurement
#The error on the weighted mean ratio is 1.525e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_LB_EB3_initcont_shift.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 1.02973
#The scaling factor for gencal is 1.015 for your comparison measurement
#The error on the weighted mean ratio is 8.186e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_LB_EB4_initcont_shift.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 1.02044
#The scaling factor for gencal is 1.010 for your comparison measurement
#The error on the weighted mean ratio is 8.103e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SB_EB0_initcont_shift.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 0.93445
#The scaling factor for gencal is 0.967 for your comparison measurement
#The error on the weighted mean ratio is 4.258e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SB_EB1_initcont_shift.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.581e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor


#Only SB EB0 is off. 
rescale_flux(vis=prefix+'_SB_EB0_initcont_shift.ms', gencalparameter=[0.967])

data_params['SB0']['flux_scaling_factor'] = 0.967
data_params['SB1']['flux_scaling_factor'] = None


"""

SB has overlapping uv ranges with both ACA and LB, so
we select an SB EB as the reference for flux scaling.

In case this source does not have ACA data, simply ignore the ACA steps in the list below.
 
If all SB EBs suffer from decoherence and cannot be used, see below

We correct flux differences >4%, if phase noise looks reasonable

If you need to re-scale fluxes, use command:
rescale_flux(vis=prefix+'_LB_EB0_initcont_shift.ms', gencalparameter=[1.044])

The general procedure is as follows:
1) check flux scaling, and if flux differences are >4%, re-scale the fluxes unless
    there is clear de-coherence (e.g. seen as a systematic decrease of scaling with UV distance)
2) do not scale those EBs with phase decoherence. Proceed with self-cal following the steps below 
   to the point that those EBs are self calibrated
3) check flux scaling again
4) if no flux scaling has been applied in 1), and you now still see a flux offset, then
    apply the flux scaling determined in step 3) to the non-self caled EBs
    and repeat the self-cal

If all SB EBs suffer from phase decoherence and cannot be used as the reference
for flux scaling:
1) concat ACA data and self-cal them in phase
2) concat them to SB data and self-cal them in phase
3) check flux offsets
4) if there are flux offsets, go back to 1), but before re-starting the process apply
    the corrections to the non-self caled ACA and SB data, and re-do steps 1) - 3).
    For this you should add additional code (essentially copy/paste the code from the first
    iteration) that repeats steps 1-3, but saves all output with different filenames. Remember
    to use the right filenames when you continue the script after step 6
5) Check flux offsets of LB EBs to a correct SB EB
6) concat LB data to ACA+SB and continue with script

"""

############ START of SB self-cal ############
#for phase cal, clean down to 6 sigma

SB_selfcal_folder = get_figures_folderpath('7_selfcal_SB_figures')
make_figures_folder(SB_selfcal_folder)

SB_cont_p0 = prefix+'_SB_contp0'
os.system('rm -rf %s.ms*' %SB_cont_p0)

#concat(vis=[f'{prefix}_SB_EB{i}_initcont_shift.ms' for i in range(number_of_EBs['SB'])],
concat(vis=[prefix+'_SB_EB0_initcont_shift_rescaled.ms',prefix+'_SB_EB1_initcont_shift.ms'],
       concatvis=SB_cont_p0+'.ms',dirtol='0.1arcsec',copypointing=False)

listobs(vis=SB_cont_p0+'.ms',listfile=SB_cont_p0+'.ms.txt',overwrite=True)

"""Define new SB mask using new center read from listobs"""
mask_ra = '18h42m57.985600s'
mask_dec = '-35.32.43.41440'

SB_mask= f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor:.3f}arcsec,'\
         +f'{mask_semiminor:.3f}arcsec], {mask_pa:.1f}deg]'

noise_annulus_SB = f"annulus[[{mask_ra}, {mask_dec}],['4.arcsec', '6.arcsec']]"

SB_tclean_wrapper_kwargs = {'mask':SB_mask,'deconvolver':'multiscale',
                            'scales':scales['SB'],'savemodel':'modelcolumn',
                            'imsize':imsize['SB'],'cellsize':cellsize['SB'],
                            'robust':0.5,'interactive':False,
                            'parallel':use_parallel,'gridder':'standard'}

#go down to ~6 sigma
tclean_wrapper(vis=SB_cont_p0+'.ms',imagename = SB_cont_p0,
               threshold = '0.4mJy', **SB_tclean_wrapper_kwargs)
estimate_SNR(SB_cont_p0+'.image', disk_mask = SB_mask,noise_mask = noise_annulus_SB)
#RXJ1842-3532_SB_contp0.image
#Beam 0.539 arcsec x 0.462 arcsec (75.69 deg)
#Flux inside disk mask: 140.79 mJy
#Peak intensity of source: 52.53 mJy/beam
#rms: 5.83e-02 mJy/beam
#Peak SNR: 901.06

rms_SB = imstat(imagename = SB_cont_p0+'.image',region = noise_annulus_SB)['rms'][0]
generate_image_png(SB_cont_p0+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_SB,10*rms_SB],
                   save_folder=SB_selfcal_folder)

""" Look for references antennas from weblog, and pick the first that are listed, overlapping with all EBs """
# both EBs: DA63, DA52, DA57, DV08

""" Get station numbers """
for ref_ant in ('DA63','DA52','DA57'):
    get_station_numbers(SB_cont_p0+'.ms',ref_ant)
#Observation ID 0: DA63@A035
#Observation ID 1: DA63@A035
#Observation ID 0: DA52@A002
#Observation ID 1: DA52@A002
#Observation ID 0: DA57@A001
#Observation ID 1: DA57@A001

SB_contspws = '0~7'
SB_refant   = 'DA63@A035,DA52@A002,DA57@A001'
SB_spw_mapping = [0,0,0,0,4,4,4,4]

#First round
SB_p1 = prefix+'_SB.p1'
os.system('rm -rf '+SB_p1)
gaincal(vis=SB_cont_p0+'.ms',caltable=SB_p1,
        gaintype='G', spw=SB_contspws,refant=SB_refant, combine='scan,spw',
        calmode='p', solint='inf', minsnr=3., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_selfcal_folder,
                             f'{prefix}_SB_gain_p1_phase_vs_time.png')
       )

""" Apply the solutions """
applycal(vis=SB_cont_p0+'.ms',spw=SB_contspws,
         spwmap=SB_spw_mapping,gaintable=[SB_p1], interp='linearPD',
         calwt=True, applymode='calonly')

SB_cont_p1 = SB_cont_p0.replace('p0','p1')
os.system('rm -rf %s.ms*' % SB_cont_p1)
split(vis=SB_cont_p0+'.ms',outputvis=SB_cont_p1+'.ms', datacolumn='corrected')

#again threshold should be ~6sigma
tclean_wrapper(vis=SB_cont_p1+'.ms',imagename = SB_cont_p1,
               threshold = '0.4mJy', **SB_tclean_wrapper_kwargs)
estimate_SNR(SB_cont_p1+'.image',disk_mask=SB_mask,noise_mask=noise_annulus_SB)
generate_image_png(SB_cont_p1+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_SB,10*rms_SB],
                   save_folder=SB_selfcal_folder)
#RXJ1842-3532_SB_contp1.image
#Beam 0.539 arcsec x 0.462 arcsec (75.69 deg)
#Flux inside disk mask: 140.80 mJy
#Peak intensity of source: 52.53 mJy/beam
#rms: 5.81e-02 mJy/beam
#Peak SNR: 904.13


#Second round
SB_p2 = SB_p1.replace('p1','p2')
os.system('rm -rf '+SB_p2)
gaincal(vis=SB_cont_p1+'.ms',caltable=SB_p2,
        gaintype='T',spw=SB_contspws,refant=SB_refant, combine='spw',
        calmode='p', solint='360s', minsnr=2., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=True,
       plotfile=os.path.join(SB_selfcal_folder,f'{prefix}_SB_gain_p2_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=SB_cont_p1+'.ms',spw=SB_contspws,
         spwmap=SB_spw_mapping, gaintable=[SB_p2], interp='linearPD',
         calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p2 = SB_cont_p1.replace('p1','p2')
os.system('rm -rf %s.ms*' % SB_cont_p2)
split(vis=SB_cont_p1+'.ms',outputvis=SB_cont_p2+'.ms',datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=SB_cont_p2+'.ms',imagename = SB_cont_p2,
               threshold = '0.4mJy', **SB_tclean_wrapper_kwargs)
estimate_SNR(SB_cont_p2+'.image', disk_mask = SB_mask,
             noise_mask = noise_annulus_SB)
generate_image_png(SB_cont_p2+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_SB,10*rms_SB],
                   save_folder=SB_selfcal_folder)
#RXJ1842-3532_SB_contp2.image
#Beam 0.539 arcsec x 0.462 arcsec (75.69 deg)
#Flux inside disk mask: 141.04 mJy
#Peak intensity of source: 52.76 mJy/beam
#rms: 5.12e-02 mJy/beam
#Peak SNR: 1031.10


#Third round
SB_p3 = SB_p2.replace('p2','p3')
os.system('rm -rf '+SB_p3)
gaincal(vis=SB_cont_p2+'.ms', caltable=SB_p3,
        gaintype='T', spw=SB_contspws,refant=SB_refant, combine='spw',
        calmode='p', solint='120s', minsnr=2., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=True,
       plotfile=os.path.join(SB_selfcal_folder,f'{prefix}_SB_gain_p3_phase_vs_time.png')
       )

""" Apply the solutions """
applycal(vis=SB_cont_p2+'.ms', spw=SB_contspws,
         spwmap = SB_spw_mapping, gaintable=[SB_p3], interp='linearPD',
         calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p3 = SB_cont_p2.replace('p2','p3')
os.system('rm -rf %s.ms*' % SB_cont_p3)
split(vis=SB_cont_p2+'.ms',outputvis=SB_cont_p3+'.ms',datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=SB_cont_p3+'.ms',imagename = SB_cont_p3,
               threshold = '0.4mJy', **SB_tclean_wrapper_kwargs)
estimate_SNR(SB_cont_p3+'.image', disk_mask = SB_mask,
             noise_mask = noise_annulus_SB)
generate_image_png(SB_cont_p3+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_SB,10*rms_SB],
                   save_folder=SB_selfcal_folder)
#RXJ1842-3532_SB_contp3.image
#Beam 0.539 arcsec x 0.462 arcsec (75.69 deg)
#Flux inside disk mask: 141.13 mJy
#Peak intensity of source: 52.86 mJy/beam
#rms: 5.14e-02 mJy/beam
#Peak SNR: 1029.24

#Fourth round
SB_p4 = SB_p3.replace('p3','p4')
os.system('rm -rf '+SB_p4)
gaincal(vis=SB_cont_p3+'.ms', caltable=SB_p4,
        gaintype='T', spw=SB_contspws,refant=SB_refant, combine='spw', calmode='p',
        solint='60s', minsnr=2., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p4,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p4,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=True,
       plotfile=os.path.join(SB_selfcal_folder,f'{prefix}_SB_gain_p4_phase_vs_time.png')
       )

applycal(vis=SB_cont_p3+'.ms', spw=SB_contspws,
         spwmap = SB_spw_mapping, gaintable=[SB_p4], interp='linearPD',
         calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p4 = SB_cont_p3.replace('p3','p4')
os.system('rm -rf %s.ms*' % SB_cont_p4)
split(vis=SB_cont_p3+'.ms',outputvis=SB_cont_p4+'.ms',datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=SB_cont_p4+'.ms',imagename = SB_cont_p4,
               threshold = '0.4mJy',**SB_tclean_wrapper_kwargs)
estimate_SNR(SB_cont_p4+'.image', disk_mask = SB_mask,
             noise_mask = noise_annulus_SB)
generate_image_png(SB_cont_p4+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_SB,10*rms_SB],
                   save_folder=SB_selfcal_folder)
#RXJ1842-3532_SB_contp4.image
#Beam 0.539 arcsec x 0.462 arcsec (75.69 deg)
#Flux inside disk mask: 141.16 mJy
#Peak intensity of source: 52.97 mJy/beam
#rms: 5.16e-02 mJy/beam
#Peak SNR: 1025.52


#we do the check for each step of the self-cal to see how things improve at each step
non_self_caled_SB_vis = SB_cont_p0
self_caled_SB_visibilities = {'p1':SB_cont_p1,
                              'p2':SB_cont_p2,
                              'p3':SB_cont_p3,
                              'p4':SB_cont_p4}
    

SB_EBs = ('EB0','EB1')
SB_EB_spws = ('0,1,2,3','4,5,6,7')

for self_cal_step,self_caled_vis in self_caled_SB_visibilities.items():
    for EB_key,spw in zip(SB_EBs,SB_EB_spws):
        nametemplate = f'{prefix}_SB_{EB_key}_{self_cal_step}_compare_amp_vs_time'
        visibilities = [self_caled_vis+'.ms',non_self_caled_SB_vis+'.ms']
        plot_amp_vs_time_comparison(
                nametemplate=nametemplate,visibilities=visibilities,spw=spw,
                uvrange=uv_ranges['SB'],output_folder=SB_selfcal_folder)


all_SB_visibilities = self_caled_SB_visibilities.copy()
all_SB_visibilities['p0'] = SB_cont_p0

for self_cal_step,vis_name in all_SB_visibilities.items():
    #split out SB EBs
    vis_ms = vis_name+'.ms'
    nametemplate = vis_ms.replace('.ms','_EB')
    split_all_obs(msfile=vis_ms,nametemplate=nametemplate)
    exported_ms = []
    for i in range(number_of_EBs['SB']):
        EB_vis = f'{nametemplate}{i}.ms'
        export_MS(EB_vis) #export MS contents into Numpy save files
        exported_ms.append(EB_vis.replace('.ms','.vis.npz'))
    for i,exp_ms in enumerate(exported_ms):
        png_filename = f'flux_comparison_SB_EB{i}_{self_cal_step}_to_{flux_ref_EB}.png'
        plot_label = os.path.join(SB_selfcal_folder,png_filename)
        estimate_flux_scale(reference=f'{prefix}_{flux_ref_EB}_initcont_shift.vis.npz',
                            comparison=exp_ms,incl=incl,PA=PA,plot_label=plot_label)
    fluxscale = [1.,]*number_of_EBs['SB']
    plot_label = os.path.join(SB_selfcal_folder,
                              f'deprojected_vis_profiles_SB_{self_cal_step}.png')
    plot_deprojected(filelist=exported_ms,fluxscale=fluxscale, PA=PA, incl=incl,
                     show_err=True,plot_label=plot_label)

#The ratio of the fluxes of RXJ1842-3532_SB_contp1_EB0.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 0.99902
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.553e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SB_contp1_EB1.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 1.00027
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.581e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SB_contp2_EB0.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 1.00251
#The scaling factor for gencal is 1.001 for your comparison measurement
#The error on the weighted mean ratio is 4.561e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SB_contp2_EB1.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 1.00327
#The scaling factor for gencal is 1.002 for your comparison measurement
#The error on the weighted mean ratio is 4.588e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SB_contp3_EB0.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 1.00356
#The scaling factor for gencal is 1.002 for your comparison measurement
#The error on the weighted mean ratio is 4.563e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SB_contp3_EB1.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 1.00459
#The scaling factor for gencal is 1.002 for your comparison measurement
#The error on the weighted mean ratio is 4.591e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#Measurement set exported to RXJ1842-3532_SB_contp0_EB1.vis.npz
#The ratio of the fluxes of RXJ1842-3532_SB_contp0_EB0.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 0.99932
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.553e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SB_contp0_EB1.vis.npz to
#RXJ1842-3532_SB_EB1_initcont_shift.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.581e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor


############ END of SB self-cal ############

""" Rescale LB EBs if needed. 'None' if no scaling is applied to that specific EB"""
data_params['LB0']['flux_scaling_factor'] = None
data_params['LB1']['flux_scaling_factor'] = None
data_params['LB2']['flux_scaling_factor'] = None
data_params['LB3']['flux_scaling_factor'] = None
data_params['LB4']['flux_scaling_factor'] = None

for i in range(number_of_EBs['LB']):
    scaling_factor = data_params[f'LB{i}']['flux_scaling_factor']
    if scaling_factor is None:
        os.system(f'cp -rf {prefix}_LB_EB{i}_initcont_shift.ms {prefix}_LB_EB{i}_initcont_shift_rescaled.ms')
    else:
        rescale_flux(vis=f'{prefix}_LB_EB{i}_initcont_shift.ms',
                     gencalparameter=[scaling_factor])


"""SELF-CAL COMBINED DATA"""
#phase cal down to 6 sigma, amp cal down to 1 sigma

LB_selfcal_folder = get_figures_folderpath('8_selfcal_SBLB_figures')
make_figures_folder(LB_selfcal_folder)

""" Merge the SB self-cal'ed ms with LB ms"""
LB_cont_p0 = prefix+'_SBLB_contp0'
os.system('rm -rf %s.ms*' % LB_cont_p0)

#make sure you choose the right SB MS here; it depends on whether you did two
#iterations of SB self-cal to deal with decoherence

#The result from the 5th round self cal. of SB is not good.
#Use the result from the 4th round
concat(vis=[SB_cont_p4+'.ms']+[f'{prefix}_LB_EB{i}_initcont_shift_rescaled.ms' for i
                                          in range(number_of_EBs['LB'])],
            concatvis=LB_cont_p0+'.ms',dirtol='0.1arcsec',copypointing=False)
#I got a warning about possibility of duplicate scan numbers, but looking at the
#listobs output, everything seems ok

listobs(vis=LB_cont_p0+'.ms',listfile=LB_cont_p0+'.ms.txt',overwrite=True)

mask_ra = '18h42m57.985600s'
mask_dec = '-35.32.43.41440'

LB_mask = f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor:.3f}arcsec,'\
         +f' {mask_semiminor:.3f}arcsec], {mask_pa:.1f}deg]'
noise_annulus_LB = f"annulus[[{mask_ra}, {mask_dec}],['4.arcsec', '6.arcsec']]"

LB_tclean_wrapper_kwargs = {'mask':LB_mask,'deconvolver':'multiscale',
                            'scales':scales['LB'],'savemodel':'modelcolumn',
                            'imsize':imsize['LB'],'cellsize':cellsize['LB'],
                            'robust':0.5,'interactive':False,
                            'parallel':use_parallel,'gridder':'standard'}


""" clean down to ~6 sigma"""
tclean_wrapper(vis=LB_cont_p0+'.ms', imagename = LB_cont_p0,
               threshold = '0.18mJy',**LB_tclean_wrapper_kwargs)
estimate_SNR(LB_cont_p0+'.image', disk_mask=LB_mask, noise_mask=noise_annulus_LB)
rms_LB = imstat(imagename = LB_cont_p0+'.image', region = noise_annulus_LB)['rms'][0]
generate_image_png(LB_cont_p0+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_selfcal_folder)
#RXJ1842-3532_SBLB_contp0.image
#Beam 0.145 arcsec x 0.116 arcsec (82.03 deg)
#Flux inside disk mask: 140.59 mJy
#Peak intensity of source: 6.75 mJy/beam
#rms: 2.80e-02 mJy/beam
#Peak SNR: 241.11


""" Look for references antennas from weblog, and pick the first that are listed, overlapping with all EBs """
""" Since we are combined SB EBs to LB EBs, ref antennas for both SB and LB are needed """
# For LB:
# EB0, EB1,: DA42, DA58, DA55
# EB2: DA42, DA58, DV04
# EB3: DA60, DA55, DV04
# EB4: DA60, DA55, DV04

# For SB, we used: DA63@A035,DA52@A002,DA57@A001
for ref_ant in ('DA60','DA42','DA55','DV04','DA58','DA63','DA52','DA57'):
    get_station_numbers(LB_cont_p0+'.ms',ref_ant)
#Observation ID 0: DA60@A042
#Observation ID 1: DA60@A042
#Observation ID 5: DA60@A042
#Observation ID 6: DA60@A042
#Observation ID 0: DA42@A047
#Observation ID 1: DA42@A047
#Observation ID 2: DA42@A047
#Observation ID 3: DA42@A047
#Observation ID 4: DA42@A047
#Observation ID 5: DA42@A047
#Observation ID 6: DA42@A047
#Observation ID 0: DA55@A043
#Observation ID 1: DA55@A043
#Observation ID 2: DA55@A043
#Observation ID 3: DA55@A043
#Observation ID 4: DA55@A043
#Observation ID 5: DA55@A043
#Observation ID 6: DA55@A043
#Observation ID 2: DV04@A007
#Observation ID 3: DV04@A007
#Observation ID 4: DV04@A007
#Observation ID 5: DV04@A007
#Observation ID 6: DV04@A007
#Observation ID 0: DA58@A045
#Observation ID 1: DA58@A045
#Observation ID 2: DA58@A045
#Observation ID 3: DA58@A045
#Observation ID 4: DA58@A045
#Observation ID 5: DA58@A045
#Observation ID 6: DA58@A045
#Observation ID 0: DA63@A035
#Observation ID 1: DA63@A035
#Observation ID 0: DA52@A002
#Observation ID 1: DA52@A002
#Observation ID 0: DA57@A001
#Observation ID 1: DA57@A001
#Observation ID 2: DA57@A104
#Observation ID 3: DA57@A104
#Observation ID 4: DA57@A104
#Observation ID 5: DA57@A104
#Observation ID 6: DA57@A104

#SB ref ant do not overlap with LB

""" Self-calibration parameters """
LB_contspws = '0~27'
LB_refant   = 'DA63@A035,DA52@A002,DA57@A001,DA60@A042,DA42@A047,DA55@A043,DV04@A007,DA58@A045'

LB_spw_mapping = [0,0,0,0,4,4,4,4,8,8,8,8,12,12,12,12,16,16,16,16,20,20,20,20,24,24,24,24]

LB_p1 = prefix+'_SBLB.p1'
os.system('rm -rf '+LB_p1)
#if you get many flagged solutions, change gaintype to 'T'
gaincal(vis=LB_cont_p0+'.ms', caltable=LB_p1, gaintype='G', spw=LB_contspws,
        refant=LB_refant, combine='scan,spw', calmode='p', solint='inf',
        minsnr=3., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(LB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,f'{prefix}_LB_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p0+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_p1], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p1 = prefix+'_SBLB_contp1'
os.system('rm -rf %s.ms*' % LB_cont_p1)
split(vis=LB_cont_p0+'.ms', outputvis=LB_cont_p1+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_p1+'.ms',imagename=LB_cont_p1,threshold='0.18mJy',
               **LB_tclean_wrapper_kwargs)
estimate_SNR(LB_cont_p1+'.image', disk_mask=LB_mask, noise_mask=noise_annulus_LB)
generate_image_png(LB_cont_p1+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_selfcal_folder)
#RXJ1842-3532_SBLB_contp1.image
#Beam 0.145 arcsec x 0.116 arcsec (82.03 deg)
#Flux inside disk mask: 139.77 mJy
#Peak intensity of source: 6.79 mJy/beam
#rms: 2.78e-02 mJy/beam
#Peak SNR: 244.19


""" Second round of phase-only self-cal """
LB_p2 = prefix+'_SBLB.p2'
os.system('rm -rf '+LB_p2)
gaincal(vis=LB_cont_p1+'.ms', caltable=LB_p2, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw,scan', calmode='p', solint='360s',
        minsnr=2., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(LB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=True,
       plotfile=os.path.join(LB_selfcal_folder,f'{prefix}_LB_gain_p2_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p1+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_p2], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p2 = prefix+'_SBLB_contp2'
os.system('rm -rf %s.ms*' % LB_cont_p2)
split(vis=LB_cont_p1+'.ms', outputvis=LB_cont_p2+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_p2+'.ms', imagename = LB_cont_p2, threshold = '0.18mJy',
               **LB_tclean_wrapper_kwargs)
estimate_SNR(LB_cont_p2+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_p2+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_selfcal_folder)
#RXJ1842-3532_SBLB_contp2.image
#Beam 0.145 arcsec x 0.116 arcsec (82.03 deg)
#Flux inside disk mask: 140.48 mJy
#Peak intensity of source: 6.94 mJy/beam
#rms: 2.54e-02 mJy/beam
#Peak SNR: 273.63


""" Third round of phase-only self-cal """
"""
Check scan length to decide whether to combine scans. If scans are 2 min, do not combine them.
If they are shorter, combine scans here
"""
LB_p3 = prefix+'_SBLB.p3'
os.system('rm -rf '+LB_p3)
gaincal(vis=LB_cont_p2+'.ms', caltable=LB_p3, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw', calmode='p', solint='120s',
        minsnr=2., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(LB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=True,
       plotfile=os.path.join(LB_selfcal_folder,f'{prefix}_LB_gain_p3_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p2+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_p3], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p3 = prefix+'_SBLB_contp3'
os.system('rm -rf %s.ms*' % LB_cont_p3)
split(vis=LB_cont_p2+'.ms', outputvis=LB_cont_p3+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_p3+'.ms', imagename = LB_cont_p3, threshold = '0.18mJy',
               **LB_tclean_wrapper_kwargs)
estimate_SNR(LB_cont_p3+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_p3+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_selfcal_folder)
#RXJ1842-3532_SBLB_contp3.image
#Beam 0.145 arcsec x 0.116 arcsec (82.03 deg)
#Flux inside disk mask: 141.29 mJy
#Peak intensity of source: 7.02 mJy/beam
#rms: 2.52e-02 mJy/beam
#Peak SNR: 278.20

tclean_wrapper(vis=LB_cont_p3+'.ms', imagename = LB_cont_p3, threshold = '0.15mJy',
               **LB_tclean_wrapper_kwargs)
estimate_SNR(LB_cont_p3+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_p3+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_selfcal_folder)
#RXJ1842-3532_SBLB_contp3.image
#Beam 0.145 arcsec x 0.116 arcsec (82.03 deg)
#Flux inside disk mask: 141.05 mJy
#Peak intensity of source: 7.02 mJy/beam
#rms: 2.51e-02 mJy/beam
#Peak SNR: 280.05

""" Fourth round of phase-only self-cal """
LB_p4 = prefix+'_SBLB.p4'
os.system('rm -rf '+LB_p4)
gaincal(vis=LB_cont_p3+'.ms', caltable=LB_p4, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw', calmode='p', solint='60s',
        minsnr=2., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p4,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(LB_p4,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=True,
       plotfile=os.path.join(LB_selfcal_folder,f'{prefix}_LB_gain_p4_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p3+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_p4], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p4 = prefix+'_SBLB_contp4'
os.system('rm -rf %s.ms*' % LB_cont_p4)
split(vis=LB_cont_p3+'.ms', outputvis=LB_cont_p4+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_p4+'.ms', imagename = LB_cont_p4, threshold = '0.15mJy',
               **LB_tclean_wrapper_kwargs)
estimate_SNR(LB_cont_p4+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_p4+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_selfcal_folder)
#RXJ1842-3532_SBLB_contp4.image
#Beam 0.145 arcsec x 0.116 arcsec (82.03 deg)
#Flux inside disk mask: 140.16 mJy
#Peak intensity of source: 7.07 mJy/beam
#rms: 2.51e-02 mJy/beam
#Peak SNR: 281.87


""" fifth round of phase-only self-cal """
LB_p5 = prefix+'_SBLB.p5'
os.system('rm -rf '+LB_p5)
gaincal(vis=LB_cont_p4+'.ms', caltable=LB_p5, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw', calmode='p', solint='20s',
        minsnr=2., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p5,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(LB_p5,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=True,
       plotfile=os.path.join(LB_selfcal_folder,f'{prefix}_LB_gain_p5_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p4+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_p5], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p5 = prefix+'_SBLB_contp5'
os.system('rm -rf %s.ms*' % LB_cont_p5)
split(vis=LB_cont_p4+'.ms', outputvis=LB_cont_p5+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_p5+'.ms', imagename = LB_cont_p5, threshold = '0.15mJy',
               **LB_tclean_wrapper_kwargs)
estimate_SNR(LB_cont_p5+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_p5+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_selfcal_folder)
#RXJ1842-3532_SBLB_contp5.image
#Beam 0.145 arcsec x 0.116 arcsec (82.03 deg)
#Flux inside disk mask: 140.04 mJy
#Peak intensity of source: 7.09 mJy/beam
#rms: 2.51e-02 mJy/beam
#Peak SNR: 282.22


""" Clean down to 1 sigma before amplitude self-cal"""

tclean_wrapper(vis=LB_cont_p5+'.ms', imagename = LB_cont_p5, threshold = '0.025mJy',
               **LB_tclean_wrapper_kwargs)
estimate_SNR(LB_cont_p5+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#RXJ1842-3532_SBLB_contp5.image
#Beam 0.145 arcsec x 0.116 arcsec (82.03 deg)
#Flux inside disk mask: 141.42 mJy
#Peak intensity of source: 7.10 mJy/beam
#rms: 2.43e-02 mJy/beam
#Peak SNR: 292.06


""" Amplitude self-cal"""
LB_ap0 = prefix+'_SBLB.ap0'
os.system('rm -rf '+LB_ap0)
gaincal(vis=LB_cont_p5+'.ms', caltable=LB_ap0, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw, scan', calmode='ap', solint='inf', minsnr=5.0,
        minblperant=4, solnorm=False)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_ap0,xaxis='time', yaxis='GainPhase',iteraxis='spw')
plotms(LB_ap0,xaxis='time', yaxis='GainAmp',iteraxis='spw')

""" Print calibration png file """
plotms(LB_ap0,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=True,
       plotfile=os.path.join(LB_selfcal_folder,f'{prefix}_LB_gain_ap0_phase_vs_time.png'))
plotms(LB_ap0,xaxis='time', yaxis='GainAmp',iteraxis='spw',exprange='all',
       overwrite=True,showgui=True,
       plotfile=os.path.join(LB_selfcal_folder,f'{prefix}_LB_gain_ap0_amp_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p5+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_ap0], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_ap0 = prefix+'_SBLB_contap0'
os.system('rm -rf %s.ms*' % LB_cont_ap0)
split(vis=LB_cont_p5+'.ms', outputvis=LB_cont_ap0+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
#clean again down to 1 sigma
tclean_wrapper(vis=LB_cont_ap0+'.ms', imagename = LB_cont_ap0, threshold = '0.025mJy',
               **LB_tclean_wrapper_kwargs)
estimate_SNR(LB_cont_ap0+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_ap0+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_selfcal_folder)
#RXJ1842-3532_SBLB_contap0.image
#Beam 0.144 arcsec x 0.114 arcsec (83.33 deg)
#Flux inside disk mask: 141.87 mJy
#Peak intensity of source: 6.97 mJy/beam
#rms: 2.39e-02 mJy/beam
#Peak SNR: 291.57


""" Try ampl self-cal on scan length intervals or 360s"""
LB_ap1 = prefix+'_SBLB.ap1'
os.system('rm -rf '+LB_ap1)
gaincal(vis=LB_cont_ap0+'.ms', caltable=LB_ap1, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw,scan', calmode='ap', solint='360s', minsnr=5.0,
        minblperant=4, solnorm=False)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_ap1,xaxis='time', yaxis='GainPhase',iteraxis='spw')
plotms(LB_ap1,xaxis='time', yaxis='GainAmp',iteraxis='spw')

""" Print calibration png file """
plotms(LB_ap1,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,f'{prefix}_LB_gain_ap1_phase_vs_time.png'))
plotms(LB_ap1,xaxis='time', yaxis='GainAmp',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,f'{prefix}_ap1_LB_gain_amp_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_ap0+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_ap1], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_ap1 = prefix+'_SBLB_contap1'
os.system('rm -rf %s.ms*' % LB_cont_ap1)
split(vis=LB_cont_ap0+'.ms', outputvis=LB_cont_ap1+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_ap1+'.ms', imagename = LB_cont_ap1,threshold = '0.025mJy',
               **LB_tclean_wrapper_kwargs)
estimate_SNR(LB_cont_ap1+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_ap1+'.image',plot_sizes=image_png_plot_sizes,
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_selfcal_folder)
#RXJ1842-3532_SBLB_contap1.image
#Beam 0.144 arcsec x 0.114 arcsec (83.33 deg)
#Flux inside disk mask: 141.99 mJy
#Peak intensity of source: 6.94 mJy/beam
#rms: 2.36e-02 mJy/beam
#Peak SNR: 294.36

#Now check the flux scaling

self_caled_LB_visibilities = {'p1':LB_cont_p1,
                              'p2':LB_cont_p2,
                              'p3':LB_cont_p3,
                              'p4':LB_cont_p4,
                              'p5':LB_cont_p5,
                              'ap0':LB_cont_ap0,
                              'ap1':LB_cont_ap1}

for vis in self_caled_LB_visibilities.values(): 
    listobs(vis=vis+'.ms',listfile=vis+'.ms.txt',overwrite=True)

LB_EBs = ('EB0','EB1','EB2','EB3','EB4')
LB_EB_spws = ('8,9,10,11','12,13,14,15','16,17,18,19','20,21,22,23','24,25,26,27') #fill out by referring to listobs output

for self_cal_step,self_caled_vis in self_caled_LB_visibilities.items():
    for EB_key,spw in zip(LB_EBs,LB_EB_spws):
        nametemplate = f'{prefix}_LB_{EB_key}_{self_cal_step}_compare_amp_vs_time'
        visibilities = [self_caled_vis+'.ms',LB_cont_p0+'.ms']
        plot_amp_vs_time_comparison(
                nametemplate=nametemplate,visibilities=visibilities,spw=spw,
                uvrange=uv_ranges['LB'],output_folder=LB_selfcal_folder)

#set to the EB of the combined SBLB data that corresponds to flux_ref_EB
SBLB_flux_ref_EB = 1 #this is SB EB1

total_number_of_EBs = number_of_EBs['SB'] + number_of_EBs['LB']
for self_cal_step,vis in self_caled_LB_visibilities.items():
    nametemplate = f'{prefix}_SBLB_cont{self_cal_step}_EB'
    split_all_obs(msfile=vis+'.ms',nametemplate=nametemplate)
    for i in range(total_number_of_EBs):
        export_MS(f'{nametemplate}{i}.ms')
    for i in range(total_number_of_EBs):
        reference = f'{nametemplate}{SBLB_flux_ref_EB}.vis.npz'
        output = f'flux_comparison_EB{i}_to_EB{SBLB_flux_ref_EB}'\
                       +f'_SBLB_{self_cal_step}.png'
        plot_label = os.path.join(LB_selfcal_folder,output)
        estimate_flux_scale(reference=reference,
                            comparison=f'{nametemplate}{i}.vis.npz',
                            incl=incl, PA=PA,uvbins = np.arange(40.,300.,20.),
                            plot_label=plot_label)
    filelist = [f'{nametemplate}{i}.vis.npz' for i in range(total_number_of_EBs)]
    fluxscale = [1.,]*total_number_of_EBs
    plot_label = os.path.join(LB_selfcal_folder,
                              f'deprojected_vis_profiles_SBLB_{self_cal_step}.png')
    plot_deprojected(filelist=filelist,fluxscale=fluxscale, PA=PA, incl=incl,
                     show_err=True,plot_label=plot_label)

#Measurement set exported to RXJ1842-3532_SBLB_contp1_EB6.vis.npz
#The ratio of the fluxes of RXJ1842-3532_SBLB_contp1_EB0.vis.npz to
#RXJ1842-3532_SBLB_contp1_EB1.vis.npz is 0.99890
#The scaling factor for gencal is 0.999 for your comparison measurement
#The error on the weighted mean ratio is 4.776e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp1_EB1.vis.npz to
#RXJ1842-3532_SBLB_contp1_EB1.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.813e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp1_EB2.vis.npz to
#RXJ1842-3532_SBLB_contp1_EB1.vis.npz is 0.95970
#The scaling factor for gencal is 0.980 for your comparison measurement
#The error on the weighted mean ratio is 9.125e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp1_EB3.vis.npz to
#RXJ1842-3532_SBLB_contp1_EB1.vis.npz is 0.97691
#The scaling factor for gencal is 0.988 for your comparison measurement
#The error on the weighted mean ratio is 1.037e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp1_EB4.vis.npz to
#RXJ1842-3532_SBLB_contp1_EB1.vis.npz is 1.01734
#The scaling factor for gencal is 1.009 for your comparison measurement
#The error on the weighted mean ratio is 1.521e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp1_EB5.vis.npz to
#RXJ1842-3532_SBLB_contp1_EB1.vis.npz is 1.01372
#The scaling factor for gencal is 1.007 for your comparison measurement
#The error on the weighted mean ratio is 8.129e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp1_EB6.vis.npz to
#RXJ1842-3532_SBLB_contp1_EB1.vis.npz is 1.01219
#The scaling factor for gencal is 1.006 for your comparison measurement
#The error on the weighted mean ratio is 8.127e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#Measurement set exported to RXJ1842-3532_SBLB_contp2_EB6.vis.npz
#The ratio of the fluxes of RXJ1842-3532_SBLB_contp2_EB0.vis.npz to
#RXJ1842-3532_SBLB_contp2_EB1.vis.npz is 0.99887
#The scaling factor for gencal is 0.999 for your comparison measurement
#The error on the weighted mean ratio is 4.776e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp2_EB1.vis.npz to
#RXJ1842-3532_SBLB_contp2_EB1.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.813e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp2_EB2.vis.npz to
#RXJ1842-3532_SBLB_contp2_EB1.vis.npz is 0.96741
#The scaling factor for gencal is 0.984 for your comparison measurement
#The error on the weighted mean ratio is 9.141e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp2_EB3.vis.npz to
#RXJ1842-3532_SBLB_contp2_EB1.vis.npz is 0.98952
#The scaling factor for gencal is 0.995 for your comparison measurement
#The error on the weighted mean ratio is 1.039e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp2_EB4.vis.npz to
#RXJ1842-3532_SBLB_contp2_EB1.vis.npz is 1.02415
#The scaling factor for gencal is 1.012 for your comparison measurement
#The error on the weighted mean ratio is 1.522e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp2_EB5.vis.npz to
#RXJ1842-3532_SBLB_contp2_EB1.vis.npz is 1.01617
#The scaling factor for gencal is 1.008 for your comparison measurement
#The error on the weighted mean ratio is 8.133e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp2_EB6.vis.npz to
#RXJ1842-3532_SBLB_contp2_EB1.vis.npz is 1.02479
#The scaling factor for gencal is 1.012 for your comparison measurement
#The error on the weighted mean ratio is 8.148e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#Measurement set exported to RXJ1842-3532_SBLB_contp3_EB6.vis.npz
#The ratio of the fluxes of RXJ1842-3532_SBLB_contp3_EB0.vis.npz to
#RXJ1842-3532_SBLB_contp3_EB1.vis.npz is 0.99891
#The scaling factor for gencal is 0.999 for your comparison measurement
#The error on the weighted mean ratio is 4.775e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp3_EB1.vis.npz to
#RXJ1842-3532_SBLB_contp3_EB1.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.813e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp3_EB2.vis.npz to
#RXJ1842-3532_SBLB_contp3_EB1.vis.npz is 0.96934
#The scaling factor for gencal is 0.985 for your comparison measurement
#The error on the weighted mean ratio is 9.143e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp3_EB3.vis.npz to
#RXJ1842-3532_SBLB_contp3_EB1.vis.npz is 0.99170
#The scaling factor for gencal is 0.996 for your comparison measurement
#The error on the weighted mean ratio is 1.040e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp3_EB4.vis.npz to
#RXJ1842-3532_SBLB_contp3_EB1.vis.npz is 1.02646
#The scaling factor for gencal is 1.013 for your comparison measurement
#The error on the weighted mean ratio is 1.522e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp3_EB5.vis.npz to
#RXJ1842-3532_SBLB_contp3_EB1.vis.npz is 1.01781
#The scaling factor for gencal is 1.009 for your comparison measurement
#The error on the weighted mean ratio is 8.136e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp3_EB6.vis.npz to
#RXJ1842-3532_SBLB_contp3_EB1.vis.npz is 1.02677
#The scaling factor for gencal is 1.013 for your comparison measurement
#The error on the weighted mean ratio is 8.151e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#Measurement set exported to RXJ1842-3532_SBLB_contp4_EB6.vis.npz
#The ratio of the fluxes of RXJ1842-3532_SBLB_contp4_EB0.vis.npz to
#RXJ1842-3532_SBLB_contp4_EB1.vis.npz is 0.99895
#The scaling factor for gencal is 0.999 for your comparison measurement
#The error on the weighted mean ratio is 4.774e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp4_EB1.vis.npz to
#RXJ1842-3532_SBLB_contp4_EB1.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.812e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp4_EB2.vis.npz to
#RXJ1842-3532_SBLB_contp4_EB1.vis.npz is 0.97007
#The scaling factor for gencal is 0.985 for your comparison measurement
#The error on the weighted mean ratio is 9.141e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp4_EB3.vis.npz to
#RXJ1842-3532_SBLB_contp4_EB1.vis.npz is 0.99277
#The scaling factor for gencal is 0.996 for your comparison measurement
#The error on the weighted mean ratio is 1.039e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp4_EB4.vis.npz to
#RXJ1842-3532_SBLB_contp4_EB1.vis.npz is 1.02728
#The scaling factor for gencal is 1.014 for your comparison measurement
#The error on the weighted mean ratio is 1.521e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp4_EB5.vis.npz to
#RXJ1842-3532_SBLB_contp4_EB1.vis.npz is 1.01823
#The scaling factor for gencal is 1.009 for your comparison measurement
#The error on the weighted mean ratio is 8.134e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp4_EB6.vis.npz to
#RXJ1842-3532_SBLB_contp4_EB1.vis.npz is 1.02821
#The scaling factor for gencal is 1.014 for your comparison measurement
#The error on the weighted mean ratio is 8.151e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#Measurement set exported to RXJ1842-3532_SBLB_contp5_EB6.vis.npz
#The ratio of the fluxes of RXJ1842-3532_SBLB_contp5_EB0.vis.npz to
#RXJ1842-3532_SBLB_contp5_EB1.vis.npz is 0.99879
#The scaling factor for gencal is 0.999 for your comparison measurement
#The error on the weighted mean ratio is 4.761e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp5_EB1.vis.npz to
#RXJ1842-3532_SBLB_contp5_EB1.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.798e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp5_EB2.vis.npz to
#RXJ1842-3532_SBLB_contp5_EB1.vis.npz is 0.96849
#The scaling factor for gencal is 0.984 for your comparison measurement
#The error on the weighted mean ratio is 9.105e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp5_EB3.vis.npz to
#RXJ1842-3532_SBLB_contp5_EB1.vis.npz is 0.98985
#The scaling factor for gencal is 0.995 for your comparison measurement
#The error on the weighted mean ratio is 1.035e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp5_EB4.vis.npz to
#RXJ1842-3532_SBLB_contp5_EB1.vis.npz is 1.01963
#The scaling factor for gencal is 1.010 for your comparison measurement
#The error on the weighted mean ratio is 1.515e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp5_EB5.vis.npz to
#RXJ1842-3532_SBLB_contp5_EB1.vis.npz is 1.01601
#The scaling factor for gencal is 1.008 for your comparison measurement
#The error on the weighted mean ratio is 8.102e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contp5_EB6.vis.npz to
#RXJ1842-3532_SBLB_contp5_EB1.vis.npz is 1.02789
#The scaling factor for gencal is 1.014 for your comparison measurement
#The error on the weighted mean ratio is 8.124e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#Measurement set exported to RXJ1842-3532_SBLB_contap0_EB6.vis.npz
#The ratio of the fluxes of RXJ1842-3532_SBLB_contap0_EB0.vis.npz to
#RXJ1842-3532_SBLB_contap0_EB1.vis.npz is 0.99854
#The scaling factor for gencal is 0.999 for your comparison measurement
#The error on the weighted mean ratio is 4.759e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contap0_EB1.vis.npz to
#RXJ1842-3532_SBLB_contap0_EB1.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.798e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contap0_EB2.vis.npz to
#RXJ1842-3532_SBLB_contap0_EB1.vis.npz is 0.99816
#The scaling factor for gencal is 0.999 for your comparison measurement
#The error on the weighted mean ratio is 9.382e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contap0_EB3.vis.npz to
#RXJ1842-3532_SBLB_contap0_EB1.vis.npz is 1.00272
#The scaling factor for gencal is 1.001 for your comparison measurement
#The error on the weighted mean ratio is 1.049e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contap0_EB4.vis.npz to
#RXJ1842-3532_SBLB_contap0_EB1.vis.npz is 1.00273
#The scaling factor for gencal is 1.001 for your comparison measurement
#The error on the weighted mean ratio is 1.489e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contap0_EB5.vis.npz to
#RXJ1842-3532_SBLB_contap0_EB1.vis.npz is 0.99506
#The scaling factor for gencal is 0.998 for your comparison measurement
#The error on the weighted mean ratio is 7.935e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contap0_EB6.vis.npz to
#RXJ1842-3532_SBLB_contap0_EB1.vis.npz is 1.00124
#The scaling factor for gencal is 1.001 for your comparison measurement
#The error on the weighted mean ratio is 7.913e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contap1_EB1.vis.npz to
#RXJ1842-3532_SBLB_contap1_EB1.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.797e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contap1_EB2.vis.npz to
#RXJ1842-3532_SBLB_contap1_EB1.vis.npz is 0.99957
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 9.388e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contap1_EB3.vis.npz to
#RXJ1842-3532_SBLB_contap1_EB1.vis.npz is 1.00217
#The scaling factor for gencal is 1.001 for your comparison measurement
#The error on the weighted mean ratio is 1.047e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contap1_EB4.vis.npz to
#RXJ1842-3532_SBLB_contap1_EB1.vis.npz is 1.00037
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 1.481e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contap1_EB5.vis.npz to
#RXJ1842-3532_SBLB_contap1_EB1.vis.npz is 0.99676
#The scaling factor for gencal is 0.998 for your comparison measurement
#The error on the weighted mean ratio is 7.945e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of RXJ1842-3532_SBLB_contap1_EB6.vis.npz to
#RXJ1842-3532_SBLB_contap1_EB1.vis.npz is 1.00077
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 7.904e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

""" Split out final continuum ms table, with a 30s timebin
"""

LB_cont_averaged = f'{prefix}_time_ave_continuum'
os.system(f'rm -rf {LB_cont_averaged}.ms*')
split(vis=LB_cont_ap1+'.ms', outputvis=LB_cont_averaged+'.ms', datacolumn='data',
      keepflags=False, timebin='30s')


"""
Now apply these solutions to the line data
"""

calibrate_linedata_folder = get_figures_folderpath('9_apply_cal_to_lines')
make_figures_folder(calibrate_linedata_folder)

""" Check that lines are not flagged in not averaged data"""
for params in data_params.values():
    plotfile = os.path.join(
                calibrate_linedata_folder,
                f'{prefix}_{params["name"]}_chan-v-amp_preselfcal_after_flagging.png')
    plotms(vis=params['vis'],
           xaxis='channel',
           yaxis='amplitude',
           field=params['field'],
           ydatacolumn='data',
           avgtime='1e8',
           avgscan=True,
           avgbaseline=True,
           coloraxis='corr',
           iteraxis='spw',
           showgui = False,
           exprange='all',
           plotfile=plotfile)


""" Apply gaintables of individual EBs"""
for params in data_params.values():
    single_EB_p1 = f'{prefix}_{params["name"]}_initcont.p1'
    vis = f'{prefix}_{params["name"]}.ms'
    applycal(vis=vis,spw='0~3',spwmap=[0,0,0,0],gaintable=[single_EB_p1],
             interp='linearPD',applymode='calonly',calwt=True)
    split(vis=vis,outputvis=vis[:-3]+'_no_ave_selfcal.ms',datacolumn='corrected')

### ALIGN DATA ###
# we re-align the no_ave data, as we have done for the "initcont" ms tables.
# We go from *_no_ave_selfcal.ms to *_no_ave_shift.ms

reference_ms = {'LB':reference_for_LB_alignment,
                'SB':reference_for_SB_alignment}
for params in data_params.values():
    unshifted_ms = f'{prefix}_{params["name"]}_no_ave_selfcal.ms'
    array_key,_ = params['name'].split('_') #LB or SB
    offset = alignment_offsets[params['name']]
    #npix and cell_size are not needed because we do not fit any offset
    alignment.align_measurement_sets(
            reference_ms=reference_ms[array_key],align_ms=[unshifted_ms],
            align_offsets=[offset],npix=None,cell_size=None)

### END OF ALINGN DATA ###


"""
re-scale the shifted *no_ave* EBs
"""


for i in range(number_of_EBs['SB']):
    scaling_factor = data_params[f'SB{i}']['flux_scaling_factor']
    if scaling_factor is None:
        os.system(f'cp -rf {prefix}_SB_EB{i}_no_ave_selfcal_shift.ms {prefix}_SB_EB{i}_no_ave_selfcal_shift_rescaled.ms')
    else:
        rescale_flux(vis=f'{prefix}_SB_EB{i}_no_ave_selfcal_shift.ms',
                     gencalparameter=[scaling_factor])


""" Concat not averaged SB data """
SB_combined = f'{prefix}_SB_no_ave_concat'
os.system('rm -rf %s.ms*' % SB_combined)
concat(vis=[f'{prefix}_SB_EB{i}_no_ave_selfcal_shift_rescaled.ms' for i
                                in range(number_of_EBs['SB'])],
       concatvis=SB_combined+'.ms', dirtol='0.1arcsec', copypointing=False)

listobs(vis=SB_combined+'.ms',listfile=SB_combined+'.ms.txt',overwrite=True)

#BE CAREFUL HERE
#Only one iteration of self cal. of SB, use SB_p1, SB_p2,...

#The result from the 5th round of self cal. of SB is not good.
#Apply the results til the 4th round
applycal(vis=SB_combined+'.ms', spw='0~7',
         gaintable=[SB_p1,SB_p2,SB_p3,SB_p4],
         spwmap = [SB_spw_mapping]*4,interp=['linearPD']*4, calwt=True,
         applymode='calonly',flagbackup=False)

SB_no_ave_selfcal = f'{prefix}_SB_no_ave_selfcal.ms'
os.system(f'rm -rf {SB_no_ave_selfcal}*')
split(vis=SB_combined+'.ms', outputvis=SB_no_ave_selfcal,datacolumn='corrected')

""" Concat not averaged LB data """

LB_combined = f'{prefix}_SBLB_no_ave_concat.ms'
os.system(f'rm -rf {LB_combined}*')

""" Rescale not averaged LB data """
for i in range(number_of_EBs['LB']):
    scaling_factor = data_params[f'LB{i}']['flux_scaling_factor']
    if scaling_factor is None:
        os.system(f'cp -rf {prefix}_LB_EB{i}_no_ave_selfcal_shift.ms {prefix}_LB_EB{i}_no_ave_selfcal_shift_rescaled.ms')
    else:
        rescale_flux(vis=f'{prefix}_LB_EB{i}_no_ave_selfcal_shift.ms',
                     gencalparameter=[scaling_factor])


concat(vis=[SB_no_ave_selfcal]+[f'{prefix}_LB_EB{i}_no_ave_selfcal_shift_rescaled.ms' for i
                                in range(number_of_EBs['LB'])],
       concatvis=LB_combined, dirtol='0.1arcsec', copypointing=False)

listobs(vis=LB_combined,listfile=LB_combined+'.txt',overwrite=True)

applycal(vis=LB_combined, spw='0~27',
         gaintable=[LB_p1,LB_p2,LB_p3,LB_p4,LB_p5,LB_ap0,LB_ap1],
         spwmap = [LB_spw_mapping]*7,interp=['linearPD']*7,
         calwt=True, applymode='calonly',flagbackup=False)

SBLB_no_ave_selfcal = f'{prefix}_SBLB_no_ave_selfcal_time_ave.ms'
os.system(f'rm -rf {SBLB_no_ave_selfcal}*')
""" time average of 30s, tests show there is no different with data without time average """
split(vis=LB_combined, outputvis=SBLB_no_ave_selfcal,
      datacolumn='corrected', timebin = '30s', keepflags=False)

listobs(vis=SBLB_no_ave_selfcal,listfile=SBLB_no_ave_selfcal+'.txt',overwrite=True)


# Flagchannels input string for LB_EB0: '0:835~3003, 2:795~3044, 3:785~3053'
# Flagchannels input string for LB_EB1: '0:835~3003, 2:795~3044, 3:785~3053'
# Flagchannels input string for LB_EB2: '0:835~3003, 2:796~3044, 3:784~3052'
# Flagchannels input string for LB_EB3: '0:835~3003, 2:796~3044, 3:784~3052'
# Flagchannels input string for LB_EB4: '0:835~3003, 2:796~3044, 3:784~3052'
# Flagchannels input string for SB_EB0: '0:838~3006, 2:791~3040, 3:791~3059'
# Flagchannels input string for SB_EB1: '0:838~3006, 2:791~3040, 3:791~3059'

#use the output of get_flagchannels at the beginning of the script to define fitspw
fitspw =  '0:838~3006, 1:0, 2:791~3040, 3:791~3059,'\
         +'4:838~3006, 5:0, 6:791~3040, 7:791~3059,'\
         +'8:835~3003, 9:0, 10:795~3044, 11:785~3053,'\
         +'12:835~3003, 13:0, 14:795~3044, 15:785~3053,'\
         +'16:835~3003, 17:0, 18:796~3044, 19:784~3052,'\
         +'20:835~3003, 21:0, 22:796~3044, 23:784~3052,'\
         +'24:835~3003, 25:0, 26:796~3044, 27:784~3052'


contsub_vis = f'{SBLB_no_ave_selfcal}.contsub'
os.system(f'rm -rf {contsub_vis}*')
uvcontsub(vis=SBLB_no_ave_selfcal, spw='0~27', fitspw=fitspw,
          excludechans=True, solint='int', fitorder=1, want_cont=False)

# Split final ms table into separate spws for 12CO, 13CO, CS and continuum

#12CO
vis_12CO = SBLB_no_ave_selfcal[:-3]+'_12CO.ms'
os.system(f'rm -rf {vis_12CO}*')
spw_12CO = '3,7,11,15,19,23,27'
split(vis=SBLB_no_ave_selfcal,outputvis=vis_12CO,spw=spw_12CO,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_12CO}.contsub',spw=spw_12CO,
      datacolumn='data', keepflags=False)

#13CO
vis_13CO = SBLB_no_ave_selfcal[:-3]+'_13CO.ms'
os.system(f'rm -rf {vis_13CO}*')
spw_13CO = '0,4,8,12,16,20,24'
split(vis=SBLB_no_ave_selfcal,outputvis=vis_13CO,spw=spw_13CO,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_13CO}.contsub',spw=spw_13CO,
      datacolumn='data', keepflags=False)

#CS
vis_CS = SBLB_no_ave_selfcal[:-3]+'_CS.ms'
os.system(f'rm -rf {vis_CS}*')
spw_CS = '2,6,10,14,18,22,26'
split(vis=SBLB_no_ave_selfcal,outputvis=vis_CS,spw=spw_CS,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_CS}.contsub',spw=spw_CS,
      datacolumn='data', keepflags=False)

#continuum spw
vis_continuum = SBLB_no_ave_selfcal[:-3]+'_contspw.ms'
os.system(f'rm -rf {vis_continuum}*')
spw_continuum = '1,5,9,13,17,21,25'
split(vis=SBLB_no_ave_selfcal,outputvis=vis_continuum,spw=spw_continuum,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_continuum}.contsub',spw=spw_continuum,
      datacolumn='data', keepflags=False)
